package com.wallellen.android.currencies;

import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * Created by walle on 1/12/16.
 */
public class JSONParser {
    private static final String TAG = JSONParser.class.getName();

    static InputStream sInputStream;
    static JSONObject sReturnJsonObject = null;
    static String sRawJsonString = "";

    public JSONParser() {
    }

    public JSONObject getJSONFromUrl(String url) {
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);

            HttpResponse response = httpClient.execute(post);
            sInputStream = response.getEntity().getContent();
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
            Log.e(TAG, ex.getMessage(), ex);
        } catch (ClientProtocolException ex) {
            ex.printStackTrace();
            Log.e(TAG, ex.getMessage(), ex);
        } catch (IOException ex) {
            ex.printStackTrace();
            Log.e(TAG, ex.getMessage(), ex);
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(sInputStream, "iso-8859-1"), 8);
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }
            sInputStream.close();
            sRawJsonString = stringBuilder.toString();
        } catch (Exception ex) {
            Log.e(TAG, ex.getMessage(), ex);
        }

        try {
            sReturnJsonObject = new JSONObject(sRawJsonString);
        } catch (JSONException ex) {
            Log.e(TAG, ex.getMessage(), ex);
        }

        return sReturnJsonObject;
    }
}
